import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { CopyOutlined } from '@ant-design/icons';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

import {
  Row, Col, Card, Input, Upload, Select, Button, message,
} from 'antd';

import { FormComponentProps } from '@ant-design/compatible/es/form';
import PageHeader from '@/components/PageHeader';

const { Option } = Select;

interface SendAPackageImportProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  INITINFO: any;
  MergeFun: (name: string, value: any) => void;
}

interface SendAPackageImportState {
  fileList: any;
  formValues: any;

}

@connect(({
  SendAPackageImport: { dataInfo },
  common: { INITINFO },
}: any) => ({ dataInfo, INITINFO }))
class SendAPackageImportElem extends Component<SendAPackageImportProps, SendAPackageImportState> {
  state = {
    fileList: [],
    formValues: {},

  }

  componentDidMount() {
    this.fetchAction('common/fetchAreaList');
  }

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const { formValues, fileList }: any = this.state;
    const {
      form: { validateFieldsAndScroll },
    } = this.props;

    validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        if (!formValues.file && fileList.length <= 0) {
          message.error('请上传文件');
        } else {
          const params = {
            ...values,
            ...formValues,
          };
          delete params.file_link;
          this.fetchAction('save', params);
        }
      }
    });
  }

  beforeUpload = (file: any) => {
    const isFileType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isFileType) {
      message.error('上传文件格式错误');
    }
    return false;
  }

  handleUpload = ({ file, fileList }: any) => {
    const { formValues } = this.state;
    if (fileList.length > 0) {
      fileList[fileList.length - 1].name = file.name.length > 5
        ? `${file.name.substring(0, 5)}....xlsx`
        : file.name;
    }
    this.setState({
      fileList: fileList.length <= 0 ? [] : [fileList[fileList.length - 1]],
      formValues: {
        ...formValues,
        file: fileList.length <= 0 ? '' : fileList[fileList.length - 1].originFileObj,
      },
    });
  }

  handleCancel = () => {
    router.goBack();
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `SendAPackageImport/${typeName}`;
    dispatch({
      type,
      payload,
    });
  }

  render() {
    const {
      form: { getFieldDecorator },
      INITINFO: { areaList },
    }: any = this.props;

    const { fileList }: any = this.state;

    return (
      <Fragment>
        <PageHeader />
        <Form hideRequiredMark onSubmit={this.handleSubmit} className="tableListForm">
          <Card title="资费导入配置" bordered={false} className="marginB20">
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Col span={24}>
                  <Form.Item label="资费名称" colon={false}>
                    {getFieldDecorator('name', {
                      rules: [{ required: true, message: '请输入资费名称' }],
                    })(
                      <Input placeholder="请输入" />,
                    )}
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item label="选择省份" colon={false}>
                    {getFieldDecorator('fromPcode', {
                      rules: [{ required: true, message: '请选择省份' }],
                    })(
                      <Select placeholder="请选择">
                        {areaList.map((item: any) => (
                          <Option key={item.id} value={item.code}>{item.name}</Option>
                        ))}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item label="是否默认" colon={false}>
                    {getFieldDecorator('isDefault', {
                      rules: [{ required: true, message: '请选择是否默认' }],
                    })(
                      <Select placeholder="请选择">
                        <Option value={0}>否</Option>
                        <Option value={1}>是</Option>
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
              </Col>
              <Col md={8} sm={24}>
                <Col span={24}>
                  <Form.Item colon={false}>
                    {getFieldDecorator('file_link', {
                      rules: [{ required: true, message: '请选择文件' }],
                    })(
                      <Upload.Dragger
                        accept=".xlsx"
                        style={{ fontSize: 12, padding: '0px 40px' }}
                        fileList={fileList}
                        beforeUpload={this.beforeUpload}
                        onChange={this.handleUpload}
                      >
                        <p className="ant-upload-drag-icon" style={{ marginBottom: 6 }}>
                          <CopyOutlined style={{ fontSize: 40 }} />
                        </p>
                        <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
                        <p className="ant-upload-hint">支持扩展名：.xlsx…</p>
                      </Upload.Dragger>,
                    )}
                  </Form.Item>
                </Col>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Button
                  type="primary"
                  htmlType="submit"
                >
                  提交
                </Button>
                <Button
                  type="primary"
                  ghost
                  className="marginL16"
                  onClick={this.handleCancel}
                >
                  取消
                </Button>
              </Col>
            </Row>
          </Card>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<SendAPackageImportProps>()(SendAPackageImportElem);
